package com.example.demo.repository;

import com.example.demo.model.Author;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class JdbcRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    public List<Author> getAllAuthors() {
        String sql = "SELECT * FROM author";

        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            Author author = new Author();
            author.setId(rs.getLong("id"));
            author.setName(rs.getString("name"));
            return author;
        });
    }

    public Author insertAuthor(Author author) {

        String sql = "INSERT INTO author (name) VALUES (?)";
        int result = jdbcTemplate.update(sql, author.getName());
        System.out.println("Author inserted with id: " + result);
        return author;
    }


    public Integer updateAuthor(Author author) {
        String sql = "UPDATE author SET name=? WHERE id=?";
        return jdbcTemplate.update(sql, author.getName(), author.getId());
    }

    public Integer deleteAuthor(Long id) {
        String sql = "DELETE FROM author WHERE id=?";
        return jdbcTemplate.update(sql, id);
    }


    public List<Author> getAllAuthorsByName(String name){
        String sql = "SELECT * FROM author WHERE name LIKE ?";
        String nameLike = "%" + name + "%";
        return jdbcTemplate.query(sql, new Object[]{nameLike}, (rs, rowNum) -> {
            Author author = new Author();
            author.setId(rs.getLong("id"));
            author.setName(rs.getString("name"));
            return author;
            });
    }
}
